﻿using System;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Text.RegularExpressions;
using AmazonBookLinker.resources;

using WindowsLive.Writer.Api;

namespace AmazonBookLinker
{
  internal static class PluginHelper
  {
    internal static string HtmlTemplateFilename
    {
      get { return Environment.GetFolderPath( Environment.SpecialFolder.LocalApplicationData ) + "\\Windows Live Writer\\AmazonBookLinker.template"; }
    }

    internal static string HtmlTemplateContent
    {
      get
      {
        if (Context.TemplateFileName != null)
        {
          return HtmlServices.HtmlDecode(HtmlServices.HtmlEncode(File.ReadAllText(Context.TemplateFileName)));
          
        }
        
        if ( !File.Exists( HtmlTemplateFilename ) )
        {
          string htmlTemplateDefaultContent = HtmlServices.HtmlDecode( Resource.HtmlTemplateDefaultContent );
          File.WriteAllText( HtmlTemplateFilename, htmlTemplateDefaultContent );
          return htmlTemplateDefaultContent;
        }

        return HtmlServices.HtmlDecode( HtmlServices.HtmlEncode( File.ReadAllText( HtmlTemplateFilename ) ) );
      }
    }


    internal static Image GetEmbeddedImage( string filename )
    {
      Assembly executingAssembly = Assembly.GetExecutingAssembly();
      using ( Stream imageResourceStream = executingAssembly.GetManifestResourceStream( "AmazonBookLinker.images." + filename ) )
      {
        if ( imageResourceStream == null )
          throw new Exception( string.Format( "Embedded image named '{0}' was not found", filename ) );

        return Image.FromStream( imageResourceStream );
      }
    }


    internal static byte[] GetByteArrayFromStream( Stream stream )
    {
      // note: Refer to http://www.yoda.arachsys.com/csharp/readbinary.html if this method is too slow
      byte[] buffer = new byte[32768];

      using ( MemoryStream memoryStream = new MemoryStream() )
      {
        while ( true )
        {
          int bytesRead = stream.Read( buffer, 0, buffer.Length );
          if ( bytesRead <= 0 )
            return memoryStream.ToArray();

          memoryStream.Write( buffer, 0, bytesRead );
        }
      }
    }

    internal static string RemoveHtmlTags(string text)
    {
       return Regex.Replace(text, @"<(.|\n)*?>", string.Empty);
    }
  }
}